package com.jar.exercise.网络编程.TCP连接.客服端和服务端;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP连接，客户端发送信息，服务端读取 并返回信息
 */
public class Demo2 {
	@Test
	public void client() throws IOException {
		//创建客户端的socket服务。指定目的主机和端口
		Socket socket = new Socket("192.168.234.1", 8888);
		//得到一个输出流
		OutputStream out = socket.getOutputStream();
		//写入内容
		out.write("张胜豪".getBytes());
		InputStream inputStream = socket.getInputStream();
		byte[] b = new byte[1024];

		int len = inputStream.read(b);
		System.out.println("收到服务器消息：" + new String(b, 0, len));
		socket.close();
	}

	@Test
	public void server() throws IOException {
		//创建serverSocket对象
		ServerSocket serverSocket = new ServerSocket(8888);
		//接收消息，阻塞状态
		Socket socket = serverSocket.accept();
		//输出消息
		InputStream input = socket.getInputStream();
		byte[] b = new byte[1024];
		int len = input.read(b);
		String s = new String(b, 0, len);
		System.out.println("接收到来自" + socket.getInetAddress().getHostAddress() + "的信息：" + s);

		OutputStream put = socket.getOutputStream();
		put.write("我收到了".getBytes());
		socket.close();
		serverSocket.close();

	}
}
